import React from 'react';
import styles from './index.less';
import { Spin, DatePicker, notification } from 'antd';
import * as echarts from 'echarts';
import _ from 'lodash';
import moment from 'moment';
import PropTypes from 'prop-types';
import styled from 'styled-components';

import PanelTitle from '#/components/PanelTitle';
import { HttpCode } from '#/utils/contacts';
import emitter from '#/utils/events';
import { TRTooltip, TRDefault } from '@/components';
import { getDataList, nextElectricityForecastPrice } from '../services';
import { TABSELECT, curveOption, formatPriceRoundUp, typeName } from './helper';

const { RangePicker } = DatePicker;

const BoxWrap = styled.div`
  background-color: var(--bg-main);
  padding: 0px 14px 14px 14px;
  margin: 0px 24px 0px 24px;
`;
const dateFormat = 'YYYY-MM-DD';
const dateFormats = 'YYYYMMDD';
export default class ElectricityPriceStatistics extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      rangePickerValue: [moment(), moment()],
      code: 'firstNew',
      dataSource: {},
      stationId: '',
      elePriceStart: moment().format(dateFormat),
      elePriceEnd: moment().format(dateFormat),
      isEmptyData: true,
      message: '暂无数据',
      updateTime: '暂无数据',
    };
  }
  componentDidMount() {
    this.getDataDetail();
    this.onWindowResize = this._updatePosition.bind(this);
    this.onMnueChange = this._updatePosition.bind(this);
    this.__eventEmitter__ = (stationId) => {
      const { rangePickerValue } = this.state;
      this.setState(
        {
          stationId: stationId,
          code: 'firstNew',
        },
        () => {
          const param = {
            endDate: rangePickerValue[0].format('YYYY-MM-DD'),
            startDate: rangePickerValue[1].format('YYYY-MM-DD'),
            stationId: stationId,
          };
          this.getDataDetail(param);
        },
      );
    };
    emitter.addListener('onChangeUnit', this.__eventEmitter__);
    window.addEventListener('resize', this.onWindowResize);
    emitter.addListener('onChangeMnue', this.onMnueChange);
  }
  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }

  _updatePosition() {
    this.timer = setTimeout(() => {
      this._myChart && this._myChart.resize();
    }, 400);
  }

  getDataDetail = async () => {
    const { code, elePriceStart, elePriceEnd, stationId } = this.state;
    const { selectStationId } = this.props;
    this.setState({ loading: true });
    const param = {
      endDate: moment(elePriceStart).format(dateFormat),
      startDate: moment(elePriceEnd).format(dateFormat),
      stationIds: [stationId ? String(stationId) : String(selectStationId)],
    };
    let res = {};
    if (param.stationIds.length < 1 || param.stationIds[0] == 'undefined') return;
    if (code === 'firstNew') {
      res = await getDataList(param);
    } else {
      res = await nextElectricityForecastPrice(param);
    }
    if (res?.statusCode === HttpCode.SUCCESS) {
      const isEmptyData = this.isEmpty(res?.results[stationId || selectStationId]);
      if (isEmptyData.length > 0) {
        this.setState({
          dataSource: res?.results,
          loading: false,
          isEmptyData: true,
          updateTime: res?.updateTime,
        });
        this.detailDataToEach(
          res?.results[stationId || selectStationId],
          res?.forecastUpdateTime,
          res?.rqdjUpdateTime,
        );
      } else {
        this.setState({
          loading: false,
          isEmptyData: false,
          message: '暂无数据',
        });
      }
    } else {
      if (res?.statusCode !== HttpCode.SYS_1004) {
        notification.error({
          message: '接口暂无权限，请联系管理员',
          description: res?.message,
          duration: 2,
        });
      }
      this.setState({
        loading: false,
        isEmptyData: false,
        message: '暂无数据',
      });
    }
  };

  isEmpty = (data) => {
    const dataArr = [];
    data.map((item) => {
      Object.entries(item.list).map(([key, value]) => {
        if (_.compact(value).length !== 0) {
          dataArr.push(key);
        }
      });
    });
    return dataArr;
  };

  detailDataToEach = (data, forecastUpdateTime, rqdjUpdateTime) => {
    const dataList = this.changeDataMap(data);
    const option = curveOption(
      { list: dataList, forecastUpdateTime, rqdjUpdateTime },
      this._tooltipFormatter.bind(this),
    );
    this._myChart.setOption(option, true);
    this._myChart.resize();
    this._onFistPostion(option);
  };

  //将null转化成-
  changeDataMap = (data) => {
    const dataList =
      data &&
      data.map((item) => {
        let list = {};
        Object.entries(item.list).map(([k, v]) => {
          list[k] = v.map((i) => {
            if (i === null || i === 'null') {
              return '-';
            }
            return i;
          });
        });
        return {
          ...item,
          list: { ...list },
        };
      });
    return dataList;
  };

  _onFistPostion(params) {
    let array = [];
    let timer = '';
    timer = params?.xAxis['data'][0];
    params?.series.forEach((item) => {
      array.push({
        name: item.name,
        tvalue: formatPriceRoundUp(item['data'][0], 3) || '-',
        value: formatPriceRoundUp(item['data'][0], 3) || '-',
        color: String(typeName[item.name]),
      });
    });
    this.__tooltip_ && this.__tooltip_.show(timer, array);
  }

  _tooltipFormatter(params) {
    let array = [];
    let timer = '';
    params.forEach((item) => {
      timer = item.axisValue?.replace(/[-|.|:]/g, '');
      array.push({
        name: item.seriesName,
        value: formatPriceRoundUp(item.value, 3),
        color: typeName[item.seriesName],
      });
    });
    this.__tooltip_ && this.__tooltip_.show(timer, array, 'powerAndelectricId', 1);
  }

  tabChange = (item) => {
    this.setState(
      {
        code: item.code,
      },
      () => {
        this.getDataDetail();
        // this.detailDataToEach(dataSource?.[item?.code])
      },
    );
  };

  onRangePicker = (date, dateStrings) => {
    this.setState(
      {
        code: 'firstNew',
        elePriceStart: dateStrings[1].replace(/\./g, '-'),
        elePriceEnd: dateStrings[0].replace(/\./g, '-'),
        rangePickerOld: [dateStrings[0].replace(/\./g, '-'), dateStrings[1].replace(/\./g, '-')],
        rangePickerValue: date,
      },
      () => {
        this.getDataDetail();
      },
    );
  };

  onOpenPicker = (open) => {
    const { elePriceStart, elePriceEnd } = this.state;
    let rangeDates = open ? [elePriceEnd, elePriceStart] : this.state.rangeOldData;
    this.setState(
      {
        rangeOldData: rangeDates,
      },
      () => {
        if (!open && !this.state.elePriceEnd.length) {
          this.setState({
            elePriceStart: this.state.rangeOldData[0],
            elePriceEnd: this.state.rangeOldData[1],
          });
        }
      },
    );
    if (open) {
      this.setState({
        elePriceStart: '',
        elePriceEnd: '',
      });
    }
  };

  render() {
    const { elePriceEnd, elePriceStart, code, loading, isEmptyData, message } = this.state;
    const { title } = this.props;
    return (
      <BoxWrap>
        <div className={styles.titleClass}>
          <PanelTitle title={title} />
          <RangePicker
            separator="-"
            format={dateFormats}
            allowClear={false}
            //  value={rangePickerValue}
            size={'small'}
            value={
              elePriceStart?.length && elePriceEnd?.length
                ? [moment(elePriceStart, 'YYYY-MM-DD'), moment(elePriceEnd, 'YYYY-MM-DD')]
                : []
            }
            onChange={this.onRangePicker.bind(this)}
            //  suffixIcon={<CaretDownOutlined />}
            onOpenChange={this.onOpenPicker.bind(this)}
            className={styles.rangePicker}
            bordered={false}
          />
        </div>
        <div className={styles.tabName}>
          {TABSELECT.map((item, index) => {
            return (
              <span
                className={item.code === code ? styles.select : ''}
                key={`electric${index}`}
                onClick={this.tabChange.bind(this, item)}
              >
                {item.name}
              </span>
            );
          })}
        </div>
        <div style={{ marginTop: '10px' }} className={styles.emptys}>
          <Spin spinning={loading}>
            <div>
              <div className={styles.toolBox}>
                <TRTooltip
                  ref={(e) => (this.__tooltip_ = e)}
                  suffixText={`单位：元/MWh`}
                  updateTime={this.state.updateTime}
                />
              </div>
              <div
                ref={(el) => el && !this._myChart && (this._myChart = echarts.init(el))}
                style={{ width: '100%', height: '280px' }}
              />
            </div>
            {!isEmptyData ? (
              <div className={styles.emptychart}>
                <TRDefault type="emptysm" description={message} />
              </div>
            ) : null}
          </Spin>
        </div>
      </BoxWrap>
    );
  }
}

ElectricityPriceStatistics.propTypes = {
  buttonPermissions: PropTypes.array,
  selectStationId: PropTypes.number,
  title: PropTypes.string,
};
